package cn.tedu.order.tcc;

import cn.tedu.order.entity.Order;
import cn.tedu.order.mapper.OrderMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

//二阶段
@Component
public class OrderTCCActionImpl implements OrderTCCAction {

    @Autowired
    private OrderMapper orderMapper;

    @Transactional
    @Override
    public boolean prepare(BusinessActionContext ctx, Long id, Long userId, Long productId, Integer count, BigDecimal money) {
        Order order = new Order(id, userId, productId, count, money,0);
        // 插入冻结订单
        orderMapper.create(order);
        //提交完成时,删除标记
        ResultHolder.removeResult(OrderTCCAction.class, ctx.getXid());
        return true;
    }

    @Transactional
    @Override
    public boolean commit(BusinessActionContext ctx) {
        //检查表示是否存在,如果不存在,说明之前已经提交过,不重复提交
        if (ResultHolder.getResult(OrderTCCAction.class, ctx.getXid())==null){
            return true;
        }
        /*
          ctx上下文对象在向第二阶段传递时,会先转成json,在重json转成上下文对象
          其中的整数可以是Integer也可能是Long
         */
        Long orderId = Long.valueOf(ctx.getActionContext("id").toString());

        //提交,吧状态修改成正常状态
        orderMapper.updateStatus(orderId, 1);
        //提交完成时,删除标记
        ResultHolder.removeResult(OrderTCCAction.class, ctx.getXid());
        return true;
    }

    @Transactional
    @Override
    public boolean rollback(BusinessActionContext ctx) {
        //检查表示是否存在,如果不存在,说明之前已经回滚过,不重复提交
        if (ResultHolder.getResult(OrderTCCAction.class, ctx.getXid())==null){
            return true;
        }
        Long orderId = Long.valueOf(ctx.getActionContext("id").toString());
        //回滚,删除订单
        orderMapper.deleteById(orderId);
        //回滚完成时,删除标记
        ResultHolder.removeResult(OrderTCCAction.class, ctx.getXid());
        return true;
    }
}
